package com.rpc;

import com.constant.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 *RPC客户端
 * 发送请求
 * 接收响应
 */
public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.POST);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //3.使用内置的交换机
        //4.声明队列
        channel.queueDeclare(Constants.RPC_REQUIRE_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);
        //5.发送请求
        String msg = "hello rpc...";
        String corrlationID = UUID.randomUUID().toString();
        AMQP.BasicProperties prop = new AMQP.BasicProperties().builder()
                        .correlationId(corrlationID)
                        .replyTo(Constants.RPC_RESPONSE_QUEUE)
                        .build();
        channel.basicPublish("",Constants.RPC_REQUIRE_QUEUE,prop,msg.getBytes());
        //6.接收响应
        //使用阻塞队列,存储响应
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String respMsg = new String(body);
                System.out.println("接到收回调消息:"+respMsg);
                //当相应消息的corrlationID和发送消息的corrlationId相同时,进行接收,将其加入到阻塞队列中
                if(corrlationID.equals(properties.getCorrelationId())){
                    response.offer(respMsg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        //从阻塞队列中取出消息
        String result = response.take();
        System.out.println("[RPC client收到消息:] "+result);
    }
}
